//
//  SYPMusicPlay_ViewController.m
//  wind
//
//  Created by SYP on 16/1/11.
//  Copyright © 2016年 李金明. All rights reserved.
//

#define RETURNLEFT (15) // 返回按钮左侧距离
#define RETURNRIGHT (10) // 返回按钮距离歌名距离
#define TOP (50) // 距离顶部的距离
#define RETURNWIDTH (25)  // 返回按钮宽度
#define RETURNHEIGHT (25) // 返回按钮高度
#define PATTERNLEFT (15) // 播放模式左侧距离
#define PATTERNRIGHT (20) // 播放列表和快进之间的距离
#define PLAYINTER (20) // 播放和上下一曲之间的距离
#define SLIDERLEFT (10) // slider 距离左侧的距离
#define SLIDERBOTTOM (100) // slider 距离下侧的距离
#define COREWIDTH (25)  // 下面button 的宽度
#define COREHEIGHT (25) // 下面button 的高度
#define TIMEWIDTH (50) // 时间Label的宽度
#define TABLEX (50) // 音乐列表的X值
#define TABLEY (200) // 音乐列表的Y值
#define TABLEWIDTH (270) // 音乐列表的宽度
#define TABLEHEIGHT (370) // 音乐列表的高度

#import <STKAudioPlayer.h>
#import "SYPMusicPlay_ViewController.h"
#import "UIImageView+WebCache.h"
#import "SYP_MusicListTableCell.h"
#import "Masonry.h"
#import "UMSocial.h"

#pragma 音乐播放的内容
#import "LJMListen_Model.h" // 储存歌曲信息的Model

// 播放模式
enum{
    SoundPlayQueue = 0,//顺序播放
    SoundPlaySingle,//单曲循环
    SoundPlayRandom,//随机播放
};

@interface SYPMusicPlay_ViewController ()<UITableViewDataSource, UITableViewDelegate, UMSocialUIDelegate>

@property (nonatomic, retain) UISlider *timeSlider; // 进度条
@property (nonatomic, retain) UIButton *playPatternButton; // 播放模式
@property (nonatomic, retain) UILabel *currentTime;
@property (nonatomic, retain) UILabel *totalTime;

@property (nonatomic, assign) NSInteger startTimerNum; // 用来记录缓冲时间
@property (nonatomic, assign) NSTimer *timer;
@property (nonatomic, retain) NSTimer *startTimer;

// 播放列表
@property (nonatomic, retain) UITableView *musicListTableV;
@property (nonatomic, retain) UITapGestureRecognizer *tapGR; // 加轻拍, 隐藏列表

#pragma 音乐播放所需属性
@property (nonatomic, retain) LJMListen_Model *tempModel; // 正在播放的音乐的Model
@property (nonatomic, retain) UIView *volumeView; // 音量控制的View
@property (nonatomic, retain) UISlider *volumeSlider; // 声音控制条
@property (nonatomic, retain) UIImageView *singImageView; //歌手图片

@property (nonatomic, retain) UIButton *collectHeart; // 收藏按钮
@property (nonatomic, retain) UIButton *shareButton; // 分享按钮

@end

@implementation SYPMusicPlay_ViewController


- (void)dealloc
{
    [_singImageView release];
    [_collectHeart release];
    [_shareButton release];
    [_singerImageV release];
    [_volumeSlider release];
    [_volumeView release];
    [_tapGR release];
    [_musicURL release];
    [_tempModel release];
    [_currentTime release];
    [_totalTime release];
    [_musicName release];
    [_singerName release];
    [_timeSlider release];
    [_playMusicName release];
    [_player release];
    [_timer release];
    [_startTimer release];
    [_MusicsArr release];
    [_musicListTableV release];
    [super dealloc];
}
// 创建音乐播放单例
+ (instancetype)shareMusicPlayVC
{
    static SYPMusicPlay_ViewController *playVC = nil;
    static dispatch_once_t one;
    
    dispatch_once(&one, ^{
        
        if (nil == playVC) {
            playVC = [[SYPMusicPlay_ViewController alloc] init];
            playVC.states = 0; // 默认为没播放状态
        }
        
    });
    
    return playVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatViews];
}

#pragma 创建音乐播放Model
- (void)creatModelWithIndex:(NSInteger)index
{
    if (0 != self.MusicsArr.count) {
        self.tempModel = self.MusicsArr[index];
    }
}


#pragma 界面将要出现刷新界面
- (void)viewWillAppear:(BOOL)animated
{
    if (1 == self.states) {
        self.playButton.selected = YES;
    } else {
        self.playButton.selected = NO;
    }
    
    if (0 != self.MusicsArr.count) {
        LJMListen_Model *mod = self.MusicsArr[self.index];
        self.singerName.text = mod.singerName;
        self.musicName.text = mod.name;
        [self.singImageView sd_setImageWithURL:[NSURL URLWithString:mod.picUrl] placeholderImage:[UIImage imageNamed:@"CD"]];
    }
    [self.musicListTableV reloadData];
}

#pragma 铺建界面
- (void)creatViews
{
    LJMListen_Model *mod = self.MusicsArr[self.index];
    
    // 歌曲播放背景
    self.singerImageV = [UIImageView new];
    self.singerImageV.userInteractionEnabled = YES;
    [self.view addSubview:self.singerImageV];

    self.singerImageV.image = [UIImage imageNamed:@"playbackground"];
    [self.singerImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [_singerImageV release];
    
    
    self.singImageView = [UIImageView new];
    [self.singerImageV addSubview:self.singImageView];
    
    [self.singImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.singerImageV).with.offset(SCREEN_WIDTH / 8);
        make.right.equalTo(self.singerImageV).with.offset(-SCREEN_WIDTH / 8);
        make.top.equalTo(self.singerImageV).with.offset(SCREEN_HEIGHT / 4);
        make.bottom.equalTo(self.singerImageV).with.offset(-SCREEN_HEIGHT / 5);
        
    }];

    // 返回按钮
    self.returnButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.returnButton setImage:[UIImage imageNamed:@"iconfont-xiala"] forState:UIControlStateNormal];
    [self.returnButton addTarget:self action:@selector(returnButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.singerImageV addSubview:self.returnButton];
    [self.returnButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.singerImageV).with.offset(RETURNLEFT);
        make.top.equalTo(self.singerImageV).with.offset(TOP);
        make.width.mas_equalTo((RETURNWIDTH));
        make.height.mas_equalTo((RETURNHEIGHT));
        
    }];
    
    // 收藏按钮
    self.collectHeart = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.collectHeart setImage:[UIImage imageNamed:@"心"] forState:UIControlStateNormal];
    [self.collectHeart setImage:[UIImage imageNamed:@"红心"] forState:UIControlStateSelected];
    [self.collectHeart addTarget:self action:@selector(CollectButtonAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.singerImageV addSubview:self.collectHeart];
    [self.collectHeart mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.singerImageV).with.offset(- 4 * RETURNLEFT);
        make.top.equalTo(self.singerImageV).with.offset(TOP);
        make.width.mas_equalTo((RETURNWIDTH));
        make.height.mas_equalTo((RETURNHEIGHT));
        
        
    }];
    
    // 分享按钮
    self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shareButton setImage:[UIImage imageNamed:@"分享"] forState:UIControlStateNormal];
    [self.shareButton addTarget:self action:@selector(shareButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.singerImageV addSubview:self.shareButton];
    
    [self.shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.singerImageV).with.offset(- RETURNLEFT);
        make.top.equalTo(self.singerImageV).with.offset(TOP);
        make.width.mas_equalTo((RETURNWIDTH));
        make.height.mas_equalTo((RETURNHEIGHT));
        
    }];
    
    
    
    
    // 歌名
    self.musicName = [UILabel new];
    [self.singerImageV addSubview:self.musicName];
    self.musicName.text = mod.name;
    self.musicName.textColor = [UIColor whiteColor];
    self.musicName.font = [UIFont systemFontOfSize:18 * SCREEN_ONE];
    [self.musicName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.returnButton.mas_right).with.offset(RETURNLEFT);
        make.top.equalTo(self.singerImageV).with.offset(TOP);
        make.right.equalTo(self.singerImageV).with.offset(-70);
        make.height.mas_equalTo(@25);
    }];
    
    // 歌手名
    self.singerName = [UILabel new];
    [self.singerImageV addSubview:self.singerName];
    [_singerName release];
    self.singerName.text = mod.singerName;
    self.singerName.textColor = [UIColor whiteColor];
    self.singerName.font = [UIFont systemFontOfSize:17 * SCREEN_ONE];
    [self.singerName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.returnButton.mas_right).with.offset(RETURNLEFT);
        make.top.equalTo(self.musicName.mas_bottom).with.offset(5 * SCREEN_ONE);
        make.right.equalTo(self.singerImageV).with.offset(-70);
        make.height.mas_equalTo(@25);
        
    }];
    
    // 进度条
    self.timeSlider = [[UISlider alloc] initWithFrame:CGRectMake(SLIDERLEFT * SCREEN_ONE, SCREEN_HEIGHT - SLIDERBOTTOM * SCREEN_ONE, SCREEN_WIDTH - 2 * SLIDERLEFT * SCREEN_ONE, 10)];
    [self.timeSlider setThumbImage:[UIImage imageNamed:@"iconfont-progressdot"] forState:UIControlStateNormal];
    [self.timeSlider addTarget:self action:@selector(timeSliderAction) forControlEvents:UIControlEventValueChanged];
    [self.singerImageV addSubview:self.timeSlider];
    [_timeSlider release];
    
    // button之间的距离
    NSInteger buttonWidth = (SCREEN_WIDTH - COREWIDTH * 5.5) / 6;
    
    // 播放模式
    self.playPatternButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    //顺序播放
    if (SoundPlayQueue == [[NSUserDefaults standardUserDefaults]  integerForKey:@"state"]) {
        self.playPatternButton.tag = SoundPlayQueue;
        [self.playPatternButton setImage:[UIImage imageNamed:@"iconfont-ttpodicon-4"] forState:UIControlStateNormal];
        NSLog(@"顺序播放");
    }
    
    //单曲播放
    else if (SoundPlaySingle == [[NSUserDefaults standardUserDefaults] integerForKey:@"state"]) {
        self.playPatternButton.tag = SoundPlaySingle;
        [self.playPatternButton setImage:[UIImage imageNamed:@"iconfont-ttpodicon-2"] forState:UIControlStateNormal];
        NSLog(@"单曲播放");
    }
    
    //随机播放
    else if (SoundPlayRandom == [[NSUserDefaults standardUserDefaults] integerForKey:@"state"]) {
        self.playPatternButton.tag = SoundPlayRandom;
        [self.playPatternButton setImage:[UIImage imageNamed:@"iconfont-ttpodicon-3"] forState:UIControlStateNormal];
        NSLog(@"随机播放");
    }
    [self.playPatternButton addTarget:self action:@selector(playPatternButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.singerImageV addSubview:self.playPatternButton];
    [self.playPatternButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.singerImageV).with.offset(buttonWidth);
        make.bottom.equalTo(self.singerImageV).with.offset(-SLIDERBOTTOM / 3);
        make.width.mas_equalTo(COREWIDTH);
        make.height.mas_equalTo(COREHEIGHT);
        
    }];
    
    // 上一曲
    self.PreviousButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.PreviousButton setImage:[UIImage imageNamed:@"previous"] forState:UIControlStateNormal];
    [self.singerImageV addSubview:self.PreviousButton];
    [self.PreviousButton addTarget:self action:@selector(PreviousButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.PreviousButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.playPatternButton.mas_right).with.offset(buttonWidth);
        make.bottom.equalTo(self.singerImageV).with.offset(-SLIDERBOTTOM / 3);
        make.width.mas_equalTo(COREWIDTH);
        make.height.mas_equalTo(COREHEIGHT);
        
    }];
    
    // 播放按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playButton setImage:[UIImage imageNamed:@"iconfont-iconfontbofang"] forState:UIControlStateNormal];
    [self.playButton setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateSelected];
    [self.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.singerImageV addSubview:self.playButton];
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.singerImageV);
        make.centerY.equalTo(self.PreviousButton.mas_centerY);
        make.width.mas_equalTo(COREWIDTH * 1.5);
        make.height.mas_equalTo(COREHEIGHT * 1.5);
        
    }];
    
    // 下一曲
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.nextButton setImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(nextButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.singerImageV addSubview:self.nextButton];
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.playButton.mas_right).with.offset(buttonWidth);
        make.bottom.equalTo(self.singerImageV).with.offset(-SLIDERBOTTOM / 3);
        make.width.mas_equalTo(COREWIDTH);
        make.height.mas_equalTo(COREHEIGHT);
        
    }];
    
    // 歌单列表
    self.musicListButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.musicListButton setImage:[UIImage imageNamed:@"iconfont-liebiao"] forState:UIControlStateNormal];
    [self.singerImageV addSubview:self.musicListButton];
    [self.musicListButton addTarget:self action:@selector(musicListButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.musicListButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.nextButton.mas_right).with.offset(buttonWidth);
        make.bottom.equalTo(self.singerImageV).with.offset(-SLIDERBOTTOM / 3);
        make.width.mas_equalTo(COREWIDTH);
        make.height.mas_equalTo(COREHEIGHT);
        
    }];
    
    // 当前时间
    self.currentTime = [[UILabel alloc] initWithFrame:CGRectMake(self.timeSlider.frame.origin.x, self.timeSlider.frame.origin.y + 15 * SCREEN_ONE, TIMEWIDTH, 20 * SCREEN_ONE)];
    self.currentTime.textColor = [UIColor whiteColor];
    self.currentTime.text = @"00:00";
    self.currentTime.font = [UIFont systemFontOfSize:SCREEN_ONE * 14];
    [self.singerImageV addSubview:self.currentTime];
    [_currentTime release];
    
    // 总时间
    self.totalTime = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - (self.timeSlider.frame.origin.x + TIMEWIDTH - 5 * SCREEN_ONE), self.timeSlider.frame.origin.y + 15 * SCREEN_ONE, TIMEWIDTH, 20 * SCREEN_ONE)];
    self.totalTime.textColor = [UIColor whiteColor];
    self.totalTime.text = @"00:00";
    self.totalTime.font = [UIFont systemFontOfSize:SCREEN_ONE * 14];
    [self.singerImageV addSubview:self.totalTime];
    [_totalTime release];
    
    
    [self creatMusicListTabel];
//    [self creatVolumeView];
}

#pragma 分享按钮
- (void)shareButtonAction
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                     appKey:@"569dabd8e0f55a4136000ffe"
                                  shareText:[NSString stringWithFormat:@"快来下载这首<<%@>>%@", self.musicName.text, self.musicURL]
                                 shareImage:[UIImage imageNamed:@"icon.png"]
                            shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToRenren,UMShareToDouban,UMShareToTencent,nil]
                                   delegate:self];
}

#pragma 收藏按钮的实现方法
- (void)CollectButtonAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
}

#pragma 上一曲
- (void)PreviousButtonAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeState" object:nil];
    switch (self.playPatternButton.tag) {
            
        case SoundPlayQueue:
            NSLog(@"开始顺序播放");
            // 界面更新
            NSInteger temp = self.index;
            if (0 != self.MusicsArr.count) {
                NSInteger temps = --temp;
                if (0 > temps) {
                    temps = self.MusicsArr.count - 1;
                }
                LJMListen_Model *mod = self.MusicsArr[temps];
                self.index = temps;
                self.musicName.text = mod.name;
                self.singerName.text = mod.singerName;
                [self.singImageView sd_setImageWithURL:[NSURL URLWithString:mod.picUrl] placeholderImage:[UIImage imageNamed:@"CD"]];
                NSMutableDictionary *dic = mod.auditionListArr[1];
                self.musicURL = dic[@"url"];
            }
            
            
            //在播放状态
            if (self.player.state == STKAudioPlayerStatePlaying) {
                
                // 停下来
                self.timeSlider.value = 0;
                self.currentTime.text = @"00:00";
                self.totalTime.text = @"00:00";
                
                // 将之前播放器停掉并且置空
                [self.player stop];
                [self.player release];
                
                // 将按钮还原成点击播放状态, 等缓冲好了开始播放了再设置成点击暂停状态
                self.playButton.selected = NO;
                self.states = 0;
                
                // 播放时的进度监视计时器清空
                
                if (1 == self.startTimer.valid) {
                    [self.startTimer invalidate];
                    self.startTimer = nil;
                }
                
                
                [self.timer invalidate];
                self.timer = nil;
                
                // 重新创建新的上一曲的音乐播放器
                [self creatPlayerWithMusicName:self.musicURL];
                
                //在暂停状态
            } else {
                
                // 点击上一曲将上一曲的播放器清空
                [self.player stop];
                [self.player release];
                
                // 将上一曲的监视进度的计时器清空
                
                if (1 == self.startTimer.valid) {
                    
                    [self.startTimer invalidate];
                    self.startTimer = nil;
                }
                
                
                [self.timer invalidate];
                self.timer = nil;
                
                // 重新创建上一曲的播放器并开始播放
                [self creatPlayerWithMusicName:self.musicURL];
                
            }

            break;
            
        case SoundPlaySingle:
            NSLog(@"开始单曲播放");
            [self singleAction]; // 单曲循环的方法
            break;
            
        case SoundPlayRandom:
            NSLog(@"开始随机播放");
            [self randomAction]; // 随机播放的方法
            break;
            
        default:
            break;
    }
}

#pragma 下一曲
- (void)nextButtonAction
{
    NSLog(@"下一曲");
    
    switch (self.playPatternButton.tag) {
            
        case SoundPlayQueue:
            NSLog(@"开始顺序播放");
            
            // 界面更新
            NSInteger temp = self.index;
            if (0 != self.MusicsArr.count) {
                NSInteger temps = ++temp;
                if (temps == self.MusicsArr.count) {
                    temps = 0;
                }
                LJMListen_Model *mod = self.MusicsArr[temps];
                self.index = temps;
                self.musicName.text = mod.name;
                self.singerName.text = mod.singerName;
                [self.singImageView sd_setImageWithURL:[NSURL URLWithString:mod.picUrl] placeholderImage:[UIImage imageNamed:@"CD"]];
                NSMutableDictionary *dic = mod.auditionListArr[1];
                self.musicURL = dic[@"url"];
                
            }
            
            // 如果是播放状态:
            if (self.player.state == STKAudioPlayerStatePlaying) {
                
                if (1 == self.startTimer.valid) {
                    [self.startTimer invalidate];
                    self.startTimer = nil;
                }
                
                // 第一步: 将进度条清零
                self.timeSlider.value = 0;
                self.currentTime.text = @"00:00";
                self.totalTime.text = @"00:00";
                
                // 第二步: 停下来之前的播放器,并清空播放器
                [self.player stop];
                [self.player release];
                
                // 第三步: 停下来之前的计时器
                [self.timer invalidate];
                self.timer = nil;
                
                // 第四步: 将播放器按钮变成点击播放状态
                self.playButton.selected = NO;
                self.states = 0;
                
                // 第五步: 重新创建播放器
                [self creatPlayerWithMusicName:self.musicURL];
                
                // 暂停状态
            } else {
                
                
                // 第一步: 将之前的播放器清空
                [self.player stop];
                [self.player release];
                
                // 第二步: 停止之前的计时器并清空
                if (1 == self.startTimer.valid) {
                    [self.startTimer invalidate];
                    self.startTimer = nil;
                }
                [self.timer invalidate];
                self.timer = nil;
                
                // 第三步: 将播放器按钮变成点击可播放状态(等缓冲完成, 开始播放的时候再设置成点击暂停状态)
                self.playButton.selected = NO;
                self.states = 0;
                
                // 第四步: 重新创建下一首的播放器
                [self creatPlayerWithMusicName:self.musicURL];
            }
            break;
            
        case SoundPlaySingle:
            NSLog(@"开始单曲播放");
            [self singleAction]; // 单曲循环的方法
            break;
            
        case SoundPlayRandom:
            NSLog(@"开始随机播放");
            [self randomAction]; // 随机播放的方法
            break;
            
        default:
            break;
    }

    
}

#pragma 单曲循环方法
- (void)singleAction
{
    // 第一步: 将进度条清零
    if (1 == self.startTimer.valid) {
        [self.startTimer invalidate];
        self.startTimer = nil;
    }
    self.timeSlider.value = 0;
    self.currentTime.text = @"00:00";
    self.totalTime.text = @"00:00";
    
    // 第二步: 停下来之前的播放器
    [self.player stop];
    [self.player release];
    
    // 第三步: 停下来之前的计时器
    [self.timer invalidate];
    self.timer = nil;
    
    // 第四步: 将播放器按钮变成暂停状态
    self.playButton.selected = NO;
    self.states = 0;
    
    // 第五步: 再次播放之前的URL
    [self creatPlayerWithMusicName:self.musicURL];
}

#pragma 随机播放的方法
- (void)randomAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeState" object:nil];
    // 1. 清零数据
    self.currentTime.text = @"00:00";
    self.totalTime.text = @"00:00";
    self.timeSlider.value = 0;
    
    // 2. 清空上次创建的播放器
    [self.player stop];
    [self.player release];
    
    // 3. 清空上次创建的计时器
    if (1 == self.startTimer.valid) {
        [self.startTimer invalidate];
        self.startTimer = nil;
    }
    [self.timer invalidate];
    self.timer = nil;
    
    // 4. 调整播放按钮
    self.playButton.selected = NO;
    self.states = 0;
    
    // 5. 创建新的播放器
    if (0 != self.MusicsArr.count) {
        
        NSInteger i = self.MusicsArr.count;
        NSInteger playIndex =arc4random() % (i - 1);
        
        // 第一步: 将正在播放第几个存到播放计数器中
        self.index = playIndex;
        
        // 第二步: 开始播放
        self.tempModel = self.MusicsArr[self.index];
        
        // 第三步: 更新播放界面的歌词歌手界面
        self.singerName.text = self.tempModel.singerName;
        self.musicName.text = self.tempModel.name;
        [self.singImageView sd_setImageWithURL:[NSURL URLWithString:self.tempModel.picUrl] placeholderImage:[UIImage imageNamed:@"CD"]];
        NSMutableDictionary *dic = self.tempModel.auditionListArr[1];
        self.musicURL = dic[@"url"];
        [self creatPlayerWithMusicName:self.musicURL];
    }
    
    // 发送通知来改变状态
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%ld", self.index] forKey:@"myIndex"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"playIndex" object:nil userInfo:dic];
}

#pragma 播放进度和进度条同步
- (void)timeSliderAction
{
    [self.player seekToTime:self.timeSlider.value];
}


#pragma 点击播放开始的计时器(用来记录缓冲时间)
- (void)startTimerAction
{
    // 缓冲计时
    self.startTimerNum++;
    
    // 缓冲时保证播放按钮处于点击可播放状态
    self.playButton.selected = NO;
    self.states = 0;
    
    
    // 开始播放了
    if (self.player.state == STKAudioPlayerStatePlaying) {
        
        NSLog(@"缓冲结束, 开始播放");
        self.playButton.selected = YES;
        self.states = 1;
        
        // 开始监控播放进度
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        
        // 将缓冲计时器清除
        [self.startTimer invalidate];
        self.startTimer = nil;
        
        // 如果30秒都未缓冲好就弹出网络不稳定的提示
    } else if (30 == self.startTimerNum) {
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"网络不稳定" preferredStyle:UIAlertControllerStyleActionSheet];
        
        [alertC addAction:[UIAlertAction actionWithTitle:@"下一曲" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self nextButton];
            
        }]];
        
        [alertC addAction:[UIAlertAction actionWithTitle:@"继续等待" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alertC animated:YES completion:^{
            
        }];
    }
}

#pragma 开始播放时的定时器监控进度
- (void)timerAction
{
    if (1 == self.startTimer.valid) {
        [self.startTimer invalidate];
        self.startTimer = nil;
    }
    self.timeSlider.maximumValue = self.player.duration;
    self.timeSlider.value = self.player.progress;
    
    // 当前时段
    NSString *currentTimes = [NSString stringWithFormat:@"%.2ld:%.2ld", (long)self.player.progress / 60, (long)self.player.progress % 60];
    self.currentTime.text = currentTimes;
    
    // 总时段
    NSString *totleTimes = [NSString stringWithFormat:@"%.2ld:%.2ld", (long)self.player.duration / 60, (long)self.player.duration % 60];
    self.totalTime.text = totleTimes;
    
    // 如果播放完毕, 进行判断
    if (self.player.duration == self.player.progress) {
        
        // 执行播放模式的选择方法
        [self switchMusicByPattern];
    }
    
}

#pragma 返回按钮的方法
- (void)returnButtonAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeState" object:nil];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    self.musicListButton.selected = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.musicListTableV.frame = CGRectMake(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 70, 0, 0);
    }];
}


#pragma 播放暂停按钮
- (void)playButtonAction:(UIButton *)sender
{
    // 如果暂无选歌
    if (0 == self.musicURL.length) {
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请选择要播放的歌曲" preferredStyle:UIAlertControllerStyleAlert];
        [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
        }]];
        [self presentViewController:alertC animated:YES completion:^{
            
            
        }];
    } else {
        
        //是点击暂停状态
        if (sender.selected) {
            
            // 如果是播放状态就暂停
            if (self.player.state == STKAudioPlayerStatePlaying){
                
                // 播放器暂停
                [self.player pause];
                
                // 将播放按钮进行设置
                sender.selected = NO;
                self.states = 0;
                NSLog(@"暂停了");
                
            }
            
            // 点击播放状态就播放
        } else {
            
            [self.player resume];
            sender.selected = YES;
            self.states = 1;
            NSLog(@"开始播放了");
            
        }
    }
}

#pragma 创建播放器
- (void)creatPlayerWithMusicName:(NSString *)musicUrl
{
    
    // 播放状态
    if (self.player.state == STKAudioPlayerStatePlaying) {
        
        // 第一步: 停止上个播放器并且清空
        [self.player stop];
        [self.player release];
        
        // 第二步: 清零数据
        self.playButton.selected = NO;
        self.states = 0;
        self.currentTime.text = @"00:00";
        self.totalTime.text = @"00:00";
        
        // 第三步: 停止上个计时器并清空
        if (1 == self.startTimer.valid) {
            [self.startTimer invalidate];
            self.startTimer = nil;
        }
        [self.timer invalidate];
        self.timer = nil;
        
        // 第四步: 开始缓存计时器
        self.startTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startTimerAction) userInfo:nil repeats:YES];
        
        // 第五步: 创建播放器
        STKAudioPlayerOptions playerOptions = {YES, YES, {50, 100, 200, 400, 800, 1600, 2600, 16000}};
        self.player = [[STKAudioPlayer alloc] initWithOptions:playerOptions];
        [self.player play:musicUrl];
    } else {
        
        
//         第一步: 停止上个计时器并清空
        if (1 == self.startTimer.valid) {
            [self.startTimer invalidate];
            self.startTimer = nil;
        }
        
        if (1 == self.timer.valid) {
            [self.timer invalidate];
            self.timer = nil;
        }

        // 第二步: 创建播放器对象player
        STKAudioPlayerOptions playerOptions = {YES, YES, {50, 100, 200, 400, 800, 1600, 2600, 16000}};
        self.player = [[STKAudioPlayer alloc] initWithOptions:playerOptions];
        
        // 第三步: 播放网络音乐
        [self.player play:musicUrl];
        
        
        // 第六步: 开启缓冲计时器
        self.startTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startTimerAction) userInfo:nil repeats:YES];
    }
    
}

#pragma 播放模式选择
- (void)playPatternButtonAction:(UIButton *)sender
{
    // 顺序播放
    if (SoundPlayQueue == sender.tag) {
        // 单曲播放
        [[NSUserDefaults standardUserDefaults] setInteger:SoundPlaySingle forKey:@"state"];
        sender.tag = SoundPlaySingle;
        [sender setImage:[UIImage imageNamed:@"iconfont-ttpodicon-2"] forState:UIControlStateNormal];
        NSLog(@"开始单曲播放");
    }
    // 单曲播放
    else if (SoundPlaySingle == sender.tag) {
        // 随机播放
        [[NSUserDefaults standardUserDefaults] setInteger:SoundPlayRandom forKey:@"state"];
        sender.tag = SoundPlayRandom;
        [sender setImage:[UIImage imageNamed:@"iconfont-ttpodicon-3"] forState:UIControlStateNormal];
        NSLog(@"开始随机播放");
    }
    // 随机播放
    else {
        // 顺序播放
        [[NSUserDefaults standardUserDefaults] setInteger:SoundPlayQueue forKey:@"state"];
        sender.tag = SoundPlayQueue;
        [sender setImage:[UIImage imageNamed:@"iconfont-ttpodicon-4"] forState:UIControlStateNormal];
        NSLog(@"开始顺序播放");
    }
}


#pragma 播放到歌曲结尾执行的方法
- (void)switchMusicByPattern
{
    switch (self.playPatternButton.tag) {
            
        case SoundPlayQueue:
            NSLog(@"开始顺序播放");
            [self nextButtonAction];  // 直接下一首
            break;
            
        case SoundPlaySingle:
            NSLog(@"开始单曲播放");
            [self singleAction]; // 单曲循环的方法
            break;
            
        case SoundPlayRandom:
            NSLog(@"开始随机播放");
            [self randomAction]; // 随机播放的方法
            break;
            
        default:
            break;
    }
}


#pragma 音乐列表按钮
- (void)musicListButtonAction:(UIButton *)sender
{
    
    // 是选中状态弹出列表
    if (sender.selected) {
        sender.selected = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.musicListTableV.frame = CGRectMake(SCREEN_WIDTH / 10 * 1.5, SCREEN_HEIGHT / 7 * 2, SCREEN_WIDTH / 10 * 7.5, SCREEN_HEIGHT / 7 * 4);
        }];
        
    } else {
        sender.selected = YES;
        [UIView animateWithDuration:0.3 animations:^{
            self.musicListTableV.frame = CGRectMake(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 70, 0, 0);
        }];
        
    }
    
}

#pragma touchesBegan方法(用来隐藏播放列表)
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"轻拍了");
    
    if (SCREEN_WIDTH - 60 != self.musicListTableV.frame.origin.x) {
        NSLog(@"能缩回去了");
        self.musicListButton.selected = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.musicListTableV.frame = CGRectMake(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 70, 0, 0);
        }];
    } else {
        if (self.volumeView.frame.origin.y != SCREEN_HEIGHT - SLIDERBOTTOM * SCREEN_ONE) {
            
            // 显示音量条
            NSLog(@"显示音量条");
            [UIView animateWithDuration:0.3 animations:^{
                
                self.volumeView.frame = CGRectMake(0, SCREEN_HEIGHT - SLIDERBOTTOM * SCREEN_ONE, SCREEN_WIDTH, SLIDERBOTTOM);
            }];
            
        } else if (self.volumeView.frame.origin.y == SCREEN_HEIGHT - SLIDERBOTTOM * SCREEN_ONE) {
            
            NSLog(@"隐藏音量条");
            [UIView animateWithDuration:0.3 animations:^{
                
                self.volumeView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SLIDERBOTTOM);
            }];
        }
    }
}

#pragma 播放界面的音量控制条
- (void)creatVolumeView
{
    // 菜单界面(音量和小功能)
    self.volumeView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT / 5)];
    self.volumeView.backgroundColor = [UIColor colorWithWhite:0.804 alpha:1.000];
    [self.singerImageV addSubview:self.volumeView];
    [_volumeView release];
    
    
}


#pragma 创建音乐列表
- (void)creatMusicListTabel
{
    self.musicListTableV = [[UITableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 70, 0, 0) style:UITableViewStylePlain];
    self.musicListTableV.backgroundColor = [UIColor colorWithWhite:0.075 alpha:0.703];
    self.musicListTableV.delegate = self;
    self.musicListTableV.dataSource = self;
    self.musicListTableV.bounces = NO;
    [self.singerImageV addSubview:self.musicListTableV];
}

// 音乐列表cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.MusicsArr.count;
}

// 区头颜色
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[[UIView alloc] init] autorelease];
    view.backgroundColor = [UIColor blackColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 150, 30)];
    label.text = @"正在播放";
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor blackColor];
    [view addSubview:label];
    [label release];
    
    return view;
}

// 区头
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

// cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

// 创建音乐列表的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    SYP_MusicListTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (nil == cell) {
        cell = [[SYP_MusicListTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    cell.numLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row];
    
    // 给列表赋值
    if (0 != self.MusicsArr.count) {
        LJMListen_Model *mod = self.MusicsArr[indexPath.row];
        cell.singerName.text = mod.singerName;
        cell.musicName.text = mod.name;
    }
    
    return cell;
}

// 点击选歌
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LJMListen_Model *mod = nil;
    NSString *url = nil;
    self.index = indexPath.row;
    if (0 != self.MusicsArr.count) {
        mod = self.MusicsArr[indexPath.row];
        self.singerName.text = mod.singerName;
        self.musicName.text = mod.name;
        [self.singImageView sd_setImageWithURL:[NSURL URLWithString:mod.picUrl] placeholderImage:[UIImage imageNamed:@"CD"]];
        NSMutableDictionary *dic = mod.auditionListArr[1];
        url = dic[@"url"];
    }
    
    if (self.player) {
        NSLog(@"已经创建好播放器");
        if (self.musicURL == url) {
            NSLog(@"点击的同一首歌");
            
            switch (self.player.state) {
                case STKAudioPlayerStatePlaying:
                    NSLog(@"播放状态, 暂停");
                    [self.player pause];
                    self.playButton.selected = NO;
                    self.states = 0;
                    
                    break;
                    
                case STKAudioPlayerStateBuffering:
                    NSLog(@"缓冲状态");
                    break;
                    
                case STKAudioPlayerStatePaused:
                    NSLog(@"暂停状态, 播放");
                    [self.player resume];
                    self.playButton.selected = YES;
                    self.states = 1;
                    
                    break;
    
                default:
                    break;
            }
        } else {
            NSLog(@"点击的不是同一首歌, 重新播放");
            [self.player stop];
            [self.player release];
            [self creatPlayerWithMusicName:url];
            self.playButton.selected = YES;
            self.states = 1;
            self.musicURL = url;
        }
   
    } else {
        NSLog(@"还没有播放器");
        [self creatPlayerWithMusicName:url];
        self.playButton.selected = YES;
        self.states = 1;
        self.musicURL = url;
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
